package com.neusoft.bizcore.activiti.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.activiti.model.ProcessFormItem;
import com.neusoft.bizcore.activiti.model.QProcessFormItem;
import com.neusoft.bizcore.activiti.repository.CustomizedProcessFormItemRepository;
import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedProcessFormItemRepositoryImpl extends AbstractRepository
        implements CustomizedProcessFormItemRepository {

    @Override
    public List<ProcessFormItem> index(final Searchable searchable) {
        final QProcessFormItem qProcessFormItem = QProcessFormItem.processFormItem;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<ProcessFormItem> query = this.query().selectFrom(qProcessFormItem);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<ProcessFormItem> search(final Pageable pageable, final Searchable searchable) {
        final QProcessFormItem qProcessFormItem = QProcessFormItem.processFormItem;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<ProcessFormItem> query = this.query().selectFrom(qProcessFormItem);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return ProcessFormItem.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QProcessFormItem qProcessFormItem = QProcessFormItem.processFormItem;

        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.and(super.containsStr(qProcessFormItem.name, searchable, "name"));
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("formCode"))) {
            where.and(super.equalsStr(qProcessFormItem.form.code, searchable, "formCode"));
        }

        return where;
    }
}
